package com.google.srclib.dataset;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.google.srclib.base.IDable;
import com.google.srclib.base.Versionable;

/**
 * 
 * @author Yuyao Liang
 * 
 */
public class RecordDataSet extends SimpleResultSet implements IDable,
		Versionable, IRecordDataset {

	public final String ID = this.getClass().getName();
	public final String Version = Messages.getString("RecordDataSet.VERSION"); //$NON-NLS-1$

	private int _count = 0;
	protected String name;

	public RecordDataSet(SimpleResultSet rs) throws SQLException {
		ResultSetMetaData meta = rs.getMetaData();
		int count = meta.getColumnCount();
		for (int i = 0; i < count; i++) {
			addColumn(meta.getColumnLabel(i + 1), meta.getColumnType(i + 1),
					meta.getColumnDisplaySize(i + 1), 0);
		}
		while (rs.next()) {
			Object[] result = new Object[count];
			for (int i = 0; i < count; i++) {
				result[i] = rs.getString(i + 1);
			}
			addRow(result);
		}
		beforeFirst();
	}

	public RecordDataSet() throws SQLException {
		super();
	}

	/**
	 * In order to add additional columns for the RecordDataset, we use
	 * Object... args as variables.
	 * 
	 * @param args
	 * @throws SQLException
	 */
	public void addRecord(Object... args) throws SQLException {
		addRow(args);
	}

	@Override
	public void addRow(Object... args) throws SQLException {
		super.addRow(args);
		_count++;
	}

	public boolean isContained(String... args) throws SQLException {
		boolean contained = false;
		for (int index = 0; index < _count; index++) {
			this.next();
			boolean same = true;
			for (int i = 0; i < args.length; i++) {
				String field = this.getString(i + 1);
				if (field == null) {
					break;
				}
				if (!field.equalsIgnoreCase(args[i])) {
					same = false;
				}
			}
			if (same) {
				this.beforeFirst();
				return same;
			}
		}
		this.beforeFirst();
		return contained;
	}

	public int getCount() {
		return _count;
	}

	public Object[] getRecord(int index) throws SQLException {
		int _index = -1;
		ResultSetMetaData meta = getMetaData();
		Object[] result = new Object[meta.getColumnCount()];
		while (next()) {
			_index++;
			if (_index == index) {
				for (int i = 0; i < meta.getColumnCount(); i++) {
					result[i] = getString(i + 1);
				}
				break;
			}
		}
		if (_index == -1) {
			return null;
		}
		return result;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getID() {
		return ID;
	}

	@Override
	public String getVersion() {
		return Version;
	}

	@Override
	// in case of release all the resource.
	public void close() {

	}

}
